<template>
  <view class="qbu">
    <!-- 标题 -->
    <view class="title">
      <view class="title-text">{{ qbu[0].biaoti }}</view>
    </view>
    <!-- 图片 -->
    <view class="img">
      <image :src="qbu[0].img" />
    </view>
    <!-- 内容 -->
    <view class="content">
      <scroll-view scroll-y style="height: 800rpx">
        <view class="content-text" v-for="(item, index) in content" :key="index">{{ item }}</view>
      </scroll-view>
    </view>
  </view>
  <view class="music-player">
    <view class="mp-btns">
      <view v-if="flag" class="mp-cover"></view>
      <view v-if="!flag" class="mp-cover mp-cover-rotate"></view>
      <view class="mp-btn-play" v-if="flag" bindtap="play">
        <text
          class="iconfont order-icon icon-bofang1"
          style="padding-left: 20rpx; font-size: 80rpx"
          @tap="startAudio(qbu[0].neiron)"
        ></text>
      </view>
      <view class="mp-btn-stop" v-if="!flag" bindtap="stop">
        <text
          class="iconfont order-icon icon-bofang"
          style="padding-left: 20rpx; font-size: 80rpx"
          @tap="startAudio1()"
        ></text>
      </view>
    </view>
    <view class="mp-slider">
      <slider
        class="mp-slider-bar"
        block-size="28"
        :max="zhonshi"
        :value="myAudioPos"
        @change="hanle_slider_change"
      ></slider>
      <view class="current-time">{{ myAudioCurrent }}</view>
      <view
        class="duration-time"
        :style="biaoxian == false ? 'display:none' : ''"
      >{{ myAudioDuration }}</view>

      <view v-if="error">音频播放出错！</view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { onLoad, onReachBottom, onBackPress, onUnload } from '@dcloudio/uni-app'
import { getTingDetail } from '@/services/kaosi'
import SHA256 from '../../utils/util/sha256'
import { ref } from 'vue'
const title = ref('')
const content = ref([])
const zuozhe = ref('')
const qbu = ref<any>([])
const flag = ref(true)
const innerAudioContext = uni.createInnerAudioContext()
onLoad(async (e: any) => {
  // 监听全局关注和顶踩事件
  console.log(e)
  console.log(e.item, '我看看111')
  let item = e.item
  let res = await getTingDetail({ item })
  console.log(res, ';444')
  qbu.value = res.data
  content.value = qbu.value[0].neiron.split(/\d+、/).filter((p) => p.trim() !== '')
  console.log(content.value, 'w d w ')
  biaoshi.value = 0
  biaoxian.value = false
})
const biaoxian = ref(false)
// 实现有道
const uuid = () => {
  console.log('调用了 uuid')
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  }
  return S4() + S4() + S4()
}
const truncate = function (q) {
  console.log('调用了 truncate')
  const size = q.length
  if (size <= 20) {
    return q
  }
  return q.slice(0, 10) + size + q.slice(size - 10, size)
}
// 时间格式化
function format(t) {
  let time = Math.floor(t / 60) >= 10 ? Math.floor(t / 60) : '0' + Math.floor(t / 60)
  t = time + ':' + ((t % 60) / 100).toFixed(2).slice(-2)
  return t
}
//loding
const biaoshi = ref(0)
const biaozhi = ref(true)
const zhonshi = ref(100)
let bianlian = 5
// 点击发音
let isShowLoading = false
const startAudio = (item) => {
  if (!isShowLoading) {
    uni.showLoading({
      title: '正在发音',
      icon: 'none',
      duration: 1000,
    })
    isShowLoading = true
  }

  console.log('触发了没有')

  const url = 'https://openapi.youdao.com/api'
  // 需要修改此处
  const appKey = '252bb1640d14eb99'
  // 需要修改此处
  const appSecret = 'X9FGNDf9qs7NvCAvKJ8DH1YFTkbVe3h4'
  const salt = uuid()
  var curtime = Math.round(new Date().getTime() / 1000)
  // 签名
  const signStr = appKey + truncate(item) + salt + curtime + appSecret
  const sign = SHA256.sha256_digest(signStr)
  console.log(salt, 'salt')
  console.log(curtime, '时间')
  console.log(signStr, '11111111111')
  console.log(sign, 'sign')
  let conunt = 0
  const result = []
  if (biaoshi.value == 0) {
    uni.request({
      url: url,
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      data: {
        q: item,
        from: 'auto',
        to: 'zh-CHS',
        appKey: appKey,
        salt: salt,
        sign: sign,
        signType: 'v3',
        curtime: curtime,
      },
      success: async function (res: any) {
        console.log(res, '我看看11111')
        let fayi = res.data['speakUrl']
        // val是需要发音的单词'https://dict.youdao.com/dictvoice?audio=Billy%20always%20listens%20to%20his%20mother.%20He%20always%20does%20what%20she%20says.%20If%20his%20mother%20says%2C%20%22Brush%20your%20teeth%2C%22%20Billy%20brushes%20his%20teeth.%20If%20his%20mother%20says%2C%20%22Go%20to%20bed%2C%22%20Billy%20goes%20to%20bed.%20Billy%20is%20a%20very%20good%20boy.%20A%20good%20boy%20listens%20to%20his%20mother.%20His%20mother%20doesn%27t%20have%20to%20ask%20him%20again.%20She%20asks%20him%20to%20do%20something%20one%20time%2C%20and%20she%20doesn%27t%20ask%20again.%20Billy%20is%20a%20good%20boy.%20He%20does%20what%20his%20mother%20asks%20the%20first%20time.%20She%20doesn%27t%20have%20to%20ask%20again.%20She%20tells%20Billy%2C%20%22You%20are%20my%20best%20child.%22%20Of%20course%20Billy%20is%20her%20best%20child.%20Billy%20is%20her%20only%20child.&le=zh&product=pc&type=null'
        // 'https://openapi.youdao.com/ttsapi?q=Nancy+wants+to+live+a+long+time.+She+wants+to+live+for+one+hundred+years.+She+is+five+years+old+now.+She+wants+to+live+95+more+years.+Then+she+will+be+100.+Her+father+is+30+years+old.+He+wants+to+live+a+long+time%2C+too.+He+wants+to+live+for+one+hundred+years.+He+wants+to+live+for+70+more+years.+%22Daddy%2C+we+will+grow+old+together%2C+okay%3F%22+Nancy+said+to+her+father.+%22Yes%2C+honey%2C+we+will+grow+old+together%2C%22+he+said+to+Nancy.+Then+Nancy+smiled.+She+gave+her+daddy+a+big+hug.&langType=en-USA&sign=1B4F9DCD4CB69AAD477A4B8F2AF0DC59&salt=1708322914694&voice=4&format=mp3&appKey=252bb1640d14eb99&ttsVoiceStrict=false&osType=api'

        uni.downloadFile({
          url: fayi,
          success: (res) => {
            if (res.statusCode === 200) {
              console.log('下载成功')
              innerAudioContext.src = res.tempFilePath
              // 在onCanplay里获取并设置音频时长和播放进度
              innerAudioContext.onCanplay(() => {
                innerAudioContext.duration //必须写，不然获取不到。。。
                setTimeout(() => {
                  console.log(innerAudioContext, '对象')

                  console.log(innerAudioContext.duration, '总时间')

                  myAudioDuration.value = format(innerAudioContext.duration)

                  myAudioCurrent.value = format(innerAudioContext.currentTime)
                }, 1000)
              })

              innerAudioContext.autoplay = true
              // innerAudioContext.loop = true
              innerAudioContext.onPlay(() => {
                console.log('开始播放')
                if (isShowLoading) {
                  uni.hideLoading()

                  isShowLoading = false
                }
              })
              //进度条变化
              innerAudioContext.onTimeUpdate(() => {
                // myAudioPos.value = (innerAudioContext.currentTime / innerAudioContext.duration) * 100
                console.log(innerAudioContext.buffered, 'dddddddddd32')

                var regex = /^\d+:\d+$/ // 例如：检查是否是 "数字:数字" 格式的字符串
                // 如果不是由用户触发的进度条变化，则不更新进度条的值
                if (!userChangeSlider) {
                  if (regex.test(myAudioDuration.value) && biaozhi.value) {
                    // 变量匹配预期的格式，可能是一个时间格式的字符串
                    console.log('11111')
                    biaoxian.value = true
                    myAudioPos.value =
                      (innerAudioContext.currentTime / innerAudioContext.duration) * 100
                    myAudioCurrent.value = format(innerAudioContext.currentTime)
                  } else {
                    // 变量不匹配预期的格式，可能是其他类型的字符串
                    console.log('2222')

                    myAudioPos.value = (innerAudioContext.currentTime / 34) * 100
                    myAudioCurrent.value = format(innerAudioContext.currentTime)
                  }
                }
                if (zhonshi.value <= myAudioPos.value) {
                  zhonshi.value += innerAudioContext.currentTime
                }
                console.log(myAudioCurrent.value, 'www')
                console.log(myAudioPos.value, 'kkkkkkkkkk')

                // 重置标志为 false
                userChangeSlider = false
              })

              //错误处理
              innerAudioContext.onError((res) => {
                console.log(res.errMsg)
                console.log(res.errCode)
                error.value = res.errMsg
                if (isShowLoading) {
                  uni.hideLoading()

                  isShowLoading = false
                }
              })

              flag.value = false
              // 播放完成处理，按钮变一下
              innerAudioContext.onEnded((res) => {
                console.log(myAudioDuration.value, '最后我看看')
                biaozhi.value = false
                flag.value = true
                zhonshi.value = myAudioPos.value
              })
              biaoshi.value++
            }
          },
        })
      },
    })
  } else {
    innerAudioContext.onCanplay(() => {
      innerAudioContext.duration //必须写，不然获取不到。。。
      setTimeout(() => {
        console.log(innerAudioContext, '对象````')

        console.log(innerAudioContext.duration, '总时间`````')

        myAudioDuration.value = format(innerAudioContext.duration)
        myAudioCurrent.value = format(innerAudioContext.currentTime)
      }, 1000)
    })
    console.log('不用请求，暂停后开始的')

    innerAudioContext.play()
    //进度条变化
    innerAudioContext.onTimeUpdate(() => {
      console.log(biaozhi.value, '我看看标志')

      console.log(innerAudioContext.currentTime, '看看')

      var regex = /^\d+:\d+$/ // 例如：检查是否是 "数字:数字" 格式的字符串
      if (!userChangeSlider) {
        if (regex.test(myAudioDuration.value) && biaozhi.value) {
          // 变量匹配预期的格式，可能是一个时间格式的字符串
          console.log('111123231')
          biaoxian.value = true
          myAudioPos.value = (innerAudioContext.currentTime / innerAudioContext.duration) * 100
          myAudioCurrent.value = format(innerAudioContext.currentTime)
        } else {
          // 变量不匹配预期的格式，可能是其他类型的字符串
          console.log('222······2')

          myAudioPos.value = (innerAudioContext.currentTime / 34) * 100
          myAudioCurrent.value = format(innerAudioContext.currentTime)
        }
      }
      // 重置标志为 false
      userChangeSlider = false
      if (zhonshi.value <= myAudioPos.value) {
        zhonshi.value += innerAudioContext.currentTime
      }
      console.log(myAudioCurrent.value, 'www````')
      console.log(myAudioPos.value, '23123123123````')
    })

    //错误处理
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
      error.value = res.errMsg
      uni.hideLoading()
    })
    flag.value = false

    // 播放完成处理，按钮变一下
    innerAudioContext.onEnded((res) => {
      console.log(myAudioDuration.value, '最后我看看``````')
      biaozhi.value = false
      zhonshi.value = myAudioPos.value
      flag.value = true
    })
  }
  // 访问有道智云API，获取识别结果
}
// 暂停听音
const startAudio1 = () => {
  console.log('触发了没有')
  flag.value = true
  biaoshi.value++
  uni.showToast({
    title: '暂停播放',
    icon: 'none',
    duration: 1000,
  })

  innerAudioContext.pause()
}
// 添加一个标志表示是否是由用户触发的进度条变化
let userChangeSlider = false
const sjian = ref(0)
var currentTime = ref(0)
// 拖动进度条，到指定位置
const hanle_slider_change = (e) => {
  const position = e.detail.value
  console.log('我点击到了')
  // 设置标志为 true，表示是用户触发的进度条变化
  userChangeSlider = true
  // var currentTime = (position / 100) * innerAudioContext.duration
  console.log(myAudioDuration.value)
  console.log(innerAudioContext.duration, '222')

  sjian.value = innerAudioContext.currentTime

  var regex = /^\d+:\d+$/ // 例如：检查是否是 "数字:数字" 格式的字符串
  if (regex.test(myAudioDuration.value)) {
    // 变量匹配预期的格式，可能是一个时间格式的字符串
    console.log('11111wwwwwwwwwwwwwwwww')

    currentTime.value = (position / 100) * innerAudioContext.duration
  } else {
    // 变量不匹配预期的格式，可能是其他类型的字符串
    console.log('2222wwwwwwwwwwwwwwwwww')

    currentTime.value = (position / 100) * 34
  }

  innerAudioContext.seek(currentTime.value)
  myAudioPos.value = position

  myAudioCurrent.value = format(currentTime.value)
  console.log(innerAudioContext.currentTime, '时间改变')
  console.log(currentTime.value, 'sjwww')
  console.log(myAudioPos.value, 'dddwwww')
  console.log(myAudioCurrent.value, 'dddddddddd')
  innerAudioContext.play()
  flag.value = false
}

// 进度条
const myAudioDuration = ref<any>('') // 视频时间
const myAudioCurrent = ref('') // 当前播放进度
const error = ref('')
const myAudioPos = ref<any>('')

onUnload(() => {
  // 监听全局关注和顶踩事件
  console.log('返回了')
  innerAudioContext.stop()
  innerAudioContext.destroy()
})
</script>

<style scoped>
@import url('../../static/assets/wxss/iconfont.css');
.qbu {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 10rpx;
}
.title {
  height: 100rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  border-bottom: 1px solid #f5f5f5;
  font-size: 30rpx;
  color: #333;
  text-align: center;
  line-height: 100rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}
.img {
  height: 300rpx;
  width: 100%;
}
.content {
  height: 200rpx;
  margin-top: 40rpx;
  margin-bottom: 10rpx;
  border-bottom: 1px solid #f5f5f5;
  font-size: 30rpx;
  color: #333;
}
.content-text {
  margin-left: 40rpx;
  margin-right: 40rpx;
  /* 发段落 */
  text-align: left;
  line-height: 40rpx;
  font-size: 30rpx;
  color: #333;
  text-indent: 2em;
  /* 两端对齐 */
  text-align: justify;
  text-justify: distribute-all-lines;
}
.music-player {
  /* 固定下方悬浮 */
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 200rpx;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
}
.mp-btns {
  width: 30%;
  height: 70%;
  /* 水平居中 */
  display: flex;
  justify-content: center; /* 水平居中 */
  /*垂直居中 */
  align-items: center;
}
.mp-slider {
  width: 70%;
  margin-top: 20rpx;
}
.current-time {
  position: relative;
  top: 10rpx;
  left: 30rpx;
  font-size: 26rpx;
  color: #333;
  text-align: left;
  line-height: 40rpx;
}
.duration-time {
  position: relative;
  top: -35rpx;
  left: 400rpx;
  font-size: 26rpx;
  color: #333;
  text-align: left;
  line-height: 40rpx;
}
</style>
